package eu.boss;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;

/**
 * Servlet used for subscription of a new account
 * @author Arnaud
 *
 */
public class SubscriptionServlet extends HttpServlet {

	private static final long serialVersionUID = -616837053601387353L;
	private DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();	
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		String login = req.getParameter("login");
		String hash = req.getParameter("hash");
		String mail=req.getParameter("email");
		boolean exists=false;	
		
		if ((login!=null)&& (hash!=null)){
			resp.setContentType("text/plain");
			
			Query query = new Query("UserList");
			for (Entity entity : datastore.prepare(query).asIterable()) {
				String s= String.valueOf(entity.getProperty("id"));
				if (s.compareTo(login)==0)
					exists=true;
			}
	
			if (!exists){
				Entity player = new Entity("UserList");
				player.setProperty("id", login);
				player.setProperty("email", mail);
				player.setProperty("hash", hash);
				datastore.put(player);
				resp.getWriter().println("SUCCESS");	
				
			}
			else
				resp.getWriter().println("ALREADY EXISTS");
			}
		
		else
			resp.getWriter().println("FAILED");		
	}
}
